//index.js
//获取应用实例
var app = getApp()
Page({
	data: {
		root:'',
		siteroot:app.setting.siteroot,
		att_url:app.setting.att_url,
		action:'jy_weishop/merch/',
		pagetitle:'我的小店' + '-' + app.setting.title,
		item:{},
		types_index:0
	},
	onReady: function (){
		//获得粉丝消息弹窗(需要时开启)
		var fansinfo = wx.getStorageSync('userInfo');
		if(!fansinfo){
			this.setData({
				ShowAuthM:true
			})
		}
	},
	onPullDownRefresh: function (){
		var the=this;
		var opt={};
		the.onLoad(opt);
		setTimeout(function(){
			wx.stopPullDownRefresh()
		},1000);
	},
	onLoad: function (opt){
		var page=this;
		wx.setNavigationBarTitle({'title':page.data.pagetitle});
		var route=page.route;
		page.setData({
			route:route,
		});
		if(opt.isgoshare){
				page.setData({
					ShowGoshare:true,
				});
			}
		if(opt.id){
			var path=route.slice(0,-6).split('/');
			app.access.plugin=path.shift();
			app.access.action=path.join('.');
			app.access.query =app.util.made_query(opt,true);
			app.access.op=opt.op?opt.op:'';
		}
		app.util.get(app.access,function(pagedata){
			//console.log('merch');console.log(app.session.menus);
			var types = []
			for(let i in pagedata.types){
				types.push(pagedata.types[i]);
			}
			if(pagedata.merch){
				pagedata.merch.logo=pagedata.merch.logo?pagedata.merch.logo:page.data.att_url+'../core/resource/images/nopic.jpg'
			}
			page.setData({
					pagedata:pagedata,
					pluginnav:app.session.menus,
					types:types
				});
			if(pagedata.op =='main' || pagedata.op =='setgoods'){
				pagedata.loading=true;
				pagedata.ctype ='all';
				setTimeout(()=>{page.get_list(1);},500);
			}
			if(pagedata.op =='main'){
				setTimeout(()=>{page.GetImagetmp(pagedata);},500);
			}
		})
	},
	onReachBottom:function(){
		var pagedata=this.data.pagedata
		if((pagedata.op=='main' || pagedata.op=='list') && pagedata.loaded==false){
			this.get_list();
		}
	},
	setlike:function(e){
		var the=this
		var data=e.currentTarget.dataset;
		var pagedata=the.data.pagedata
		app.util.post('jy_merch/myshop/like/',data,function(res){
			app.util.msg(res);
			pagedata.merch.islike=pagedata.merch.islike==1?0:1;
			the.setData({
				'pagedata.merch':pagedata.merch
			})
		});
	},
	info_login:function(e){
		//根据openid为用户登陆，此处尝试获取用户信息
		app.util.getUserInfo(e);
		this.setData({
			ShowAuthM:false
		})
	},
  	click:function(evt){
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		app.util[data.func](data.params);
	},
	click_tab:function(evt){
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		app.util.tab(data.params);
	},
	formSubmit:function(event){
		var value=event.detail.value;
		var pagedata = this.data.pagedata
		var post={}
		post.title = value.title
		post.subtitle = value.subtitle
		post.unit = value.unit
		post.price = value.price
		post.total = value.total
		post.image = pagedata.item.image
		post.images = pagedata.item.images
		post.weight = pagedata.item.weight
		app.util.post('jy_weishop/merch/addgoods/',post);
	},
	setMyshop:function(e){
		var value=e.detail.value;
		console.log('value');console.log(value);
		var pagedata = this.data.pagedata
		if(!value.merchname){
			app.util.message('商户名称不能为空','error');
			return false;
		}
		if(!value.salecate){
			app.util.message('商户类型不能为空','error');
			return false;
		}
		if(!value.desc){
			app.util.message('商户描述不能为空','error');
			return false;
		}
		pagedata.item.merchname = value.merchname
		pagedata.item.salecate = value.salecate
		pagedata.item.desc = value.desc
		pagedata.item.realname = value.realname
		pagedata.item.mobile = value.mobile
		pagedata.item.topimg = pagedata.item.topimg
		app.util.post('jy_weishop/merch/set/',pagedata.item);
	},
	moveup:function(e){
		var the = this
		var pagedata =the.data.pagedata
		var data = e.currentTarget.dataset
		pagedata.item.images.splice(data.index-1,0,data.p);
		pagedata.item.images.splice(data.index+1,1)
		the.setData({
			pagedata:pagedata
		})
	},
	bindPickerChange:function(e){
		var the = this
		var pagedata = the.data.pagedata
		pagedata.item.type = e.detail.value
		the.setData({
			types_index:e.detail.value,
			'pagedata.item.type':pagedata.item.type
		})
	},
	del:function(e){
		var the = this
		var pagedata =the.data.pagedata
		var data = e.currentTarget.dataset
		pagedata.item.images.splice(data.index,1)
		the.setData({
			pagedata:pagedata
		})
	},
	setstatus:function(e){
		var the = this
		var pagedata = the.data.pagedata
		var data = e.currentTarget.dataset
		pagedata.list[data.index].status= pagedata.list[data.index].status?0:1
		app.util.post('jy_weishop/merch/setstatus/',{'id':data.id})
		the.setData({
			pagedata:pagedata
		})
	},
	iskefu:function(){
		var the = this
		var pagedata = the.data.pagedata
		pagedata.item.iskefu=pagedata.item.iskefu =='0'?'1':'0'
		console.log(pagedata.item.iskefu);
		the.setData({
			'pagedata.item.iskefu':pagedata.item.iskefu
		})
	},
	iscommission:function(){
		var the = this
		var pagedata = the.data.pagedata
		pagedata.item.iscommission=pagedata.item.iscommission == '0'?'1':'0'
		
		the.setData({
			'pagedata.item.iscommission':pagedata.item.iscommission
		})
	},
	is_share:function(){
		var the = this
		var pagedata = the.data.pagedata
		pagedata.item.is_share=pagedata.item.is_share == '0'?'1':'0'
		
		the.setData({
			'pagedata.item.is_share':pagedata.item.is_share
		})
	},
	delgoods:function(e){
		var the = this
		var pagedata = the.data.pagedata
		var value = e.currentTarget.dataset
		wx.showModal({
			title: '提示',
			content: '确定删除？',
			success(res){
				if (res.confirm) {
					app.util.post('jy_weishop/merch/delgoods/',{'id':value.id},function(res){
						app.util.message(res,'','jy_weishop/merch/setgoods/')
					})
				} else if (res.cancel) {
				}
			}
		})
	},
	sale_goods:function(e){
		var the = this
		var pagedata = the.data.pagedata
		var value = e.currentTarget.dataset
		wx.showModal({
			title: '提示',
			content: '确定该代销商品？',
			success(res){
				if (res.confirm) {
					app.util.post('jy_weishop/merch/sale_goods/',{'id':value.id},function(res){
						//app.util.message(res)
					})
				} else if (res.cancel) {
				}
			}
		})
	},
	copy_goods:function(e){
		var the = this
		var pagedata = the.data.pagedata
		var value = e.currentTarget.dataset
		wx.showModal({
			title: '提示',
			content: '确定复制？',
			success(res){
				if (res.confirm) {
					app.util.post('jy_weishop/merch/up_goods/',{'id':value.id},function(res){
						app.util.message(res)
					})
				} else if (res.cancel) {
				}
			}
		})
	},
	copy_merch:function(){
		var the = this
		var pagedata = the.data.pagedata
		wx.showModal({
			title: '提示',
			content: '确认复制他的店铺吗？复制后，你的店铺描述，LOGO会变成复制的',
			success(res){
				if (res.confirm) {
					app.util.post('jy_weishop/merch/copy_merch/',{},function(res){
						app.util.message('复制成功')
					})
				} else if (res.cancel) {
					
				}
			}
		})
	},
	show_shopset:function(){
		var the = this
		var pagedata = the.data.pagedata
		pagedata.show_shopset = pagedata.show_shopset?0:1
		the.setData({
			'pagedata.show_shopset':pagedata.show_shopset
		})
	},
	// 搜索框文本内容的显示
	inputBind: function (event) {
		this.setData({
		  keywords: event.detail.value
		})
	},
	//搜索执行按钮
	query: function (event) {
		var page = this;
		app.util.get('jy_weishop/merch/main/keyword=' + page.data.keywords, function (pagedata) {
		  page.setData({
			pagedata: pagedata
		  });
		});
	},
	get_list:function(e){
		var the = this
		var pagedata = the.data.pagedata
		if(e && e!='all' && e!=1){
			var data = e.currentTarget.dataset
		}else{
			var data={};
			data.order='all'
		}
		if(data.order){
			pagedata.loaded = false
			pagedata.params.page=1;
			pagedata.list=[];
			pagedata.params.order=data.order;
			pagedata.ctype =data.order
			pagedata.params.cid='';
			the.setData({
				'pagedata.ctype':data.order
			})
		}else if(data.cid){
			pagedata.loaded = false
			pagedata.params.page=1;
			pagedata.params.cid=data.cid;
			pagedata.params.order='';
			pagedata.list =[];
			pagedata.ctype =data.cid
			the.setData({
				'pagedata.ctype':data.cid
			})
		}else if(pagedata.loaded){
			return;
		}
		if(pagedata.op =='setgoods'){
			pagedata.params.setgoods=1;
		}
		var query=app.util.made_query(pagedata.params);
		app.util.get('jy_weishop/merch/list/'+query,function(res){
			pagedata.loading=false;
			if(res=='none'){
				pagedata.loaded=true;
				return;
			}
			if(!Array.isArray(res)){
				app.util.message('获取数据失败！');
				return;
			}
			if(res.length<2){
				pagedata.loaded=true;
			}
			if(!pagedata.list){
				pagedata.list=[];
			}
			res.forEach(function(row){
				pagedata.list.push(row);
			});
			pagedata.ctype = data.order
			pagedata.params.page++;
			the.setData({
				pagedata:pagedata
			})
		});
		
	},
	choose_file:function(e){
		var the =this
		var modaldata=the.data.modaldata?the.data.modaldata:{}
		if(modaldata.params){
			var title= modaldata.params.title?modaldata.params.title:'';
		}else{
			var title='';
		}
		modaldata.type=modaldata.type?modaldata.type:'one';
		modaldata.source_type=modaldata.source_type?modaldata.source_type:'image';
		if(e && e.currentTarget && e.currentTarget.dataset){
			var data=e.currentTarget.dataset;
			var op=data.op?data.op:'';
			var page=data.page?data.page:1;
			var group_id=data.group_id?data.group_id:'';
			if(!group_id && modaldata.params && modaldata.params.group_id){
				group_id=modaldata.params.group_id;
			}
			if(data.file){
				modaldata.filename=data.file;
			}
			if(data.tovalue){
				modaldata.tovalue=data.tovalue;
			}
			if(data.thumb){
				modaldata.thumbname=data.thumb;
			}
			modaldata.type=data.type?data.type:'one';
			modaldata.source_type=data.source_type?data.source_type:modaldata.source_type;
		}else{
			var op=modaldata.op?modaldata.op:'list';
			var group_id=modaldata.params.group_id?modaldata.params.group_id:-2;
			var page=1;
		}
		var action='core/tools.choose_file//type='+modaldata.type+'&op='+op+'&source_type='+modaldata.source_type+'&group_id='+group_id+'&title='+title+'&page='+page
		app.util.get(action,function(res){
			modaldata.file_list=modaldata.file_list?modaldata.file_list:[];
			modaldata=Object.assign(modaldata,res);
			the.setData({
				modaldata: modaldata,
				showchoosefile:true,
			})
		});
	},
	choose_file_tabop:function(e){
		var the =this
		var modaldata =the.data.modaldata
		var data=e.currentTarget.dataset;
		the.setData({
			'modaldata.op': data.op,
		})
	},
	choose_file_splice:function(e){
		var the =this
		var modaldata =the.data.modaldata
		var data=e.currentTarget.dataset;
		modaldata.file_list.splice(data.index,1);
		the.setData({
			'modaldata.file_list': modaldata.file_list,
		})
	},
	choose_file_keyword: function (e) {
		var the = this
		the.setData({
		  'modaldata.params.title': e.detail.value
		})
	},
	choose_file_image: function (e) {
		var the = this
		var modaldata =the.data.modaldata
		var pagedata =the.data.pagedata
		var att_url=the.data.att_url
		var file=modaldata.file;
		var thumb=modaldata.thumb?modaldata.thumb:'';
		if(e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.index>=0){
			var data=e.currentTarget.dataset;
			var file=modaldata.list[data.index].attachment;
			var thumb=modaldata.list[data.index].thumb;
			thumb=thumb?thumb:'';
		}
		if(modaldata.type=='more'){
			if(modaldata.tovalue){
						pagedata[modaldata.tovalue][modaldata.filename]=pagedata[modaldata.tovalue][modaldata.filename]?pagedata[modaldata.tovalue][modaldata.filename]:[]
						pagedata[modaldata.tovalue][modaldata.filename].push(file);
			}else{
						pagedata[modaldata.filename].push(file);
			}
			the.setData({
					  pagedata: pagedata,
			})
		}else{
			if(file && modaldata.filename){
				    if(modaldata.tovalue){
						pagedata[modaldata.tovalue][modaldata.filename]=file
					}else{
						pagedata[modaldata.filename]=file
					}					
					if(modaldata.thumbname){
						if(modaldata.tovalue){
							pagedata[modaldata.tovalue][modaldata.thumbname]=thumb
						}else{
							pagedata[modaldata.thumbname]=thumb
						}
					}
					console.log(pagedata);
					the.setData({
					  pagedata: pagedata,
					})
			}
		}
		the.setData({
				   showchoosefile:false,
		})		
	},
	choose_file_images:function(){
		var the = this
		var modaldata =the.data.modaldata
		var res=';'+modaldata.file_list.join(';')+';';
		the.setData({
			'file_list': res,
		})
	},
	up_file:function(){
		var the =this
		var modaldata =the.data.modaldata	
		app.util.up_file(modaldata.source_type,function(res,thumb){
			modaldata.file=res
			if(thumb){
				modaldata.thumb=thumb
			}
			the.setData({
				modaldata: modaldata,
			})	
		});
	},
	phonecall:function (e) {
		var data = e.currentTarget.dataset
		wx.makePhoneCall({
		  phoneNumber: data.phone //
		});
	},
	//画布 
	promisify: api => {
		return (options, ...params) => {
		  return new Promise((resolve, reject) => {
			const extras = {
			  success: resolve,
			  fail: reject
			}
			api({ ...options, ...extras }, ...params)
		  })
		}
	},
	GetImagetmp: function(e){
		var the=this;
		var pagedata=e
		var att_url=the.data.att_url
		const wxGetImageInfo = the.promisify(wx.getImageInfo)
		pagedata.merch.appcode=pagedata.merch.appcode?pagedata.merch.appcode:'../core/resource/images/nopic.jpg'
		Promise.all([
			// 商品图
			wxGetImageInfo({
				src: pagedata.merch.logo
			}),
			// 二维码
			wxGetImageInfo({
				src: att_url+pagedata.merch.appcode
			}),
		]).then(res => {
			app.imagetmps=res
			console.log('imagetmps');console.log(app.imagetmps);
		});
	},
	share_canvas: function(){
			var the=this;
			if(app.imagetmps){
				app.util.showLoading();
			}else{
				app.util.msg('绘图忙碌,请稍后尝试！');
				return false;
			}
			setTimeout(function(){the.CanvasContext()},500);
	},
	//绘制画
	CanvasContext: function(){
			var the=this;
			var pagedata=the.data.pagedata
			var att_url=the.data.att_url
			var screenWidth=280
			var screenHeight=app.screenHeight * 0.94
			console.log('screenHeight');console.log(screenHeight);
			console.log('screenWidth');console.log(screenWidth);
			var titleHight=19
			const ctx = wx.createCanvasContext('shareCanvas')
			ctx.setFillStyle('white');//填充白色
			ctx.fillRect(2, 2, screenWidth-4 , 386);//画出矩形白色背景
			ctx.restore();
			// 文字1
			//ctx.setTextAlign('center')    // 文字居中
			ctx.setFillStyle('#000000')  // 文字颜色：黑色
			ctx.setFontSize(12)         // 文字字号：px
			// 商品标题
			ctx.fillText(pagedata.merch.title1+' ', 10,  308)
			ctx.fillText(pagedata.merch.title2+' ', 10,  328)
			ctx.setFillStyle('#999')  // 文字颜色：黑色
			ctx.setFontSize(12)         // 文字字号：px
			ctx.fillText('扫右侧我的小店二维码,有惊喜哦', 10,  355)
			// 二维码文字
			ctx.setFillStyle('#999')  // 文字颜色：黑色
			//ctx.fillText('扫《'+app.setting.title+'》二维码', screenWidth-270,  295)
			// 二维码文字
			ctx.setFontSize(10)         // 文字字号：px
			ctx.fillText('微信扫一扫', screenWidth-70, 373)
			// 小程序码
			ctx.drawImage(app.imagetmps[1].path, screenWidth-80, 290, 70, 70)
			// 商品图
			ctx.drawImage(app.imagetmps[0].path, 2, 2, screenWidth-4,280)
			ctx.restore();
			ctx.draw()
			the.setData({
				showsetqrcode:true
			})
			the.getcanvasToPath()
	},
	//获取海报路径
	getcanvasToPath:function(){
		var the = this;
		var screenWidth=280
		var screenHeight=390
		setTimeout(function () {
			wx.canvasToTempFilePath({
				x: 0,
				y: 0,
				width: screenWidth,
				height: screenHeight,
				destWidth: screenWidth*2.6,
				destHeight: screenHeight*2.6,
				canvasId: 'shareCanvas',
				success: function (res) {
					console.log('生成');console.log(res)
					setTimeout(function () {app.util.hideLoading()},1000);
					the.setData({
						savedImgUrl: res.tempFilePath
					})
				},
				fail: function (res){
					console.log('失败');console.log(res)
					setTimeout(function () {app.util.hideLoading()},1000);
				}
			})
		}, 1000)
	},
	//保存海报
	saveImageToPhoto: function () {
		var that = this;
		setTimeout(function () {
			if (that.data.savedImgUrl != "") {
				wx.saveImageToPhotosAlbum({
					filePath: that.data.savedImgUrl,
					//filePath:'/resource/images/share-bg01.png',
					success: function () {
						wx.showModal({
							title: '保存图片成功',
							content: '图片已经保存到相册，快去分享吧！',
							showCancel: false,
							success: function (res) {
								that.setData({
									canvasShow: false,
									showsetqrcode:false
								})
							},
							fail: function (res) { },
								complete: function (res) { },
						});
					},
					fail: function(res) {
						console.log(res);
						if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {
							wx.showModal({
								title: '保存图片失败',
								content: '您已取消保存图片到相册！',
								showCancel: false
							});
						} else {
							wx.showModal({
								title: '提示',
								content: '保存图片失败，您可以点击确定设置获取相册权限后再尝试保存！',
								complete: function(res) {
									console.log(res);
									if (res.confirm) {
									wx.openSetting({}) //打开小程序设置页面，可以设置权限
									} else {
									wx.showModal({
										title: '保存图片失败',
										content: '您已取消保存图片到相册！',
										showCancel: false
									});
									}
								}
							});
						}
					}
				})
			}
		}, 1500)
	},
	onShareAppMessage: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		if (res.from === 'button') {
		}
		var path=the.data.route+'?'+app.access.query+"&plugin_name="+app.plugin_name+'&id='+pagedata.merch.id;
		if(app.access.op){
			path +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			path +='&fromuser='+pagedata.fromuser;
		}
		return {
		  title: the.data.pagetitle,
		  path: path,
		  desc: app.setting.sharedesc,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
	onShareTimeline: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		var query=app.access.query
		if(app.access.op){
			query +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			query +='&fromuser='+pagedata.fromuser;
		}
		query +='&isgoshare=1'
		return {
		  title: the.data.pagetitle,
		  query: query,
		  desc: app.setting.sharedesc,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
	
});